//
//  AppDelegate.m
//  PPDL
//
//  Created by 王洋 on 2019/7/23.
//  Copyright © 2019 王洋. All rights reserved.
//

#import <WXApi.h>
#import <AlipaySDK/AlipaySDK.h>

#import "AppDelegate.h"
#import "TTGTSDKManager.h"
#import "TTThirdSDKManager.h"
#import "TTNotificationHandler.h"
#import "PPTabBarController.h"
#import <GTSDK/GeTuiSdk.h>     // GetuiSdk头文件应用

#import <UserNotifications/UserNotifications.h>
#import "OnboardingViewController.h"
#import "OnboardingContentViewController.h"
#import "PPLeadViewController.h"

@interface AppDelegate ()<GeTuiSdkDelegate, UNUserNotificationCenterDelegate, WXApiDelegate>

@property (nonatomic, assign) BOOL done;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [[TTThirdSDKManager shareManager] initThirdSDK];
    [self initThirdSDK];
    
    //检查是否启动引导页
    if (![[TTGlobalStatus sharedStatus].startGuideStatus isEqualToString:@"1"]) {
        self.window.rootViewController = [self generateStandardOnboardingVC];
    } else {
        [self setupNormalRootViewController];
    }

    application.statusBarStyle = UIStatusBarStyleLightContent;
    [self.window makeKeyAndVisible];
    
    NSTimeInterval delayDuration = 1.5;
    NSTimer *connectionTimer = [NSTimer scheduledTimerWithTimeInterval:delayDuration target:self selector:@selector(timerFired:) userInfo:nil repeats:NO];
    [[NSRunLoop currentRunLoop] addTimer:connectionTimer forMode:NSDefaultRunLoopMode];
    do {
        // 设置1.0秒检测做一次do...while的循环
        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0]];
    } while (!self.done);
    
    return YES;
}

-(void)timerFired:(NSTimer *)timer {
    self.done = YES;
}


- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
//    [[SDImageCache sharedImageCache] setValue:nil forKey:@"memCache"];
}

//willback 如锁屏
- (void)applicationWillResignActive:(UIApplication *)application {
//    [[TTGlobalStatus sharedStatus] refreshTime];
}

//didback  已经进入后台
- (void)applicationDidEnterBackground:(UIApplication *)application {

}

//将要进入前台
- (void)applicationWillEnterForeground:(UIApplication *)application {
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"PP_AppWillEnterForegroundNoti" object:nil userInfo:nil];
    
}

//已经进入前台
- (void)applicationDidBecomeActive:(UIApplication *)application {
//    [[TTGlobalStatus sharedStatus] refreshTime];
}


- (void)applicationWillTerminate:(UIApplication *)application {
//    [[TTGlobalStatus sharedStatus] refreshTime];
}

#pragma mark SDK------------------------------SDK--------------------------------初始化
- (void)initThirdSDK {
    [TTGTSDKManager initSDKWithDelegate:self];
    [self registerRemoteNotification];
}

#pragma mark push------------push-------------GeTui SDK Method----------push--------push
#pragma mark push------注册APNS
- (void)registerRemoteNotification {
    if (@available(iOS 11.0, *))
    {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {

        }];
    }
    else
    {
        UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types
                                                                                 categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }
    
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    
    
    // 注册push权限，用于显示本地推送
    [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
}

#pragma mark push------SDK收到透传消息回调
- (void)GeTuiSdkDidReceivePayloadData:(NSData *)payloadData andTaskId:(NSString *)taskId andMsgId:(NSString *)msgId andOffLine:(BOOL)offLine fromGtAppId:(NSString *)appId {
    //收到个推消息
//    NSString *payloadMsg = nil;
//    if (payloadData) {
//        payloadMsg = [[NSString alloc] initWithBytes:payloadData.bytes length:payloadData.length encoding:NSUTF8StringEncoding];
//    }
    /*
     {
     id = 13421;
     type = 1412;
     }
     */
    
//    NSDictionary *responseObject = [Utilities dictionaryWithJsonString:payloadData];
//    [[TTNotificationHandler sharedInstance] showRemoteNotificationWithDict:responseObject];
}

#pragma mark push------SDK启动成功返回cid
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
}

#pragma mark  push------APP已经接收到“远程”通知(推送) - 透传推送消息
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {

    if ([userInfo isKindOfClass:[NSDictionary class]] && [userInfo.allKeys containsObject:@"nim"]) {
        
        [SVProgressHUD showWithStatus:userInfo[@"aps"][@"alert"]];
        [SVProgressHUD dismissWithDelay:0.5];
    } else {
        
//        [[TTNotificationHandler sharedInstance] clickRemoteNotificationWithDict:@{}];
        PP_jumpModel *model = [[PP_jumpModel alloc] init];
        [[TTNotificationHandler sharedInstance] clickRemoteNotificationWithModel:model];
        
        //静默推送收到消息后也需要将APNs信息传给个推统计
        [TTGTSDKManager GTSDK_handleRemoteNotification:userInfo];
    }
    
    completionHandler(UIBackgroundFetchResultNewData);
}

#pragma mark push------远程通知注册成功委托
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    // [3]:向个推服务器注册deviceToken 为了方便开发者，建议使用新方法
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    [TTGTSDKManager GTSDK_registerDeviceToken:token];
//    [[TTNeteaseIMManager sharedManager] NeteaseRegisterPushToken:deviceToken];
}

#pragma mark  push------iOS10以后  为处理 APNs 通知点击事件，统计有效用户点击数
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0

//  iOS 10: App在前台获取到通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler  API_AVAILABLE(ios(10.0)){
    
    // 根据APP需要，判断是否要提示用户Badge、Sound、Alert
    if (@available(iOS 10.0, *)) {
        completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
    } else {
        // Fallback on earlier versions
    }
}

#pragma mark  push------iOS 10: 点击通知进入App时触发，在该方法内统计有效用户点击数
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler  API_AVAILABLE(ios(10.0)){

    NSDictionary *dic = response.notification.request.content.userInfo;
    NSString * payload = [dic valueForKey:@"payload"];
    NSDictionary *payloadDic = [Utilities dictionaryWithString:payload];
    
    if ([payloadDic isKindOfClass:[NSDictionary class]] && [payloadDic.allKeys containsObject:@"type"]){
        
        PP_jumpModel *model = [[PP_jumpModel alloc] init];
        model.type = ([[payloadDic valueForKey:@"type"] integerValue]);
        model.ID = [payloadDic valueForKey:@"id"];
        model.ext = [payloadDic valueForKey:@"ext"];
        [[TTNotificationHandler sharedInstance] clickRemoteNotificationWithModel:model];
    }
    
    [TTGTSDKManager GTSDK_handleRemoteNotification:response.notification.request.content.userInfo];
    completionHandler();
}

#endif

#pragma mark 引导页------------------引导页 ------------------ ROOT逻辑 ------------------
- (void)setupNormalRootViewController {
    self.window.backgroundColor = [UIColor whiteColor];
    PPTabBarController *tabBarController = [PPTabBarController shareTabbar];
    self.window.rootViewController = tabBarController;
}

- (void)handleOnboardingCompletion {
    [self setupNormalRootViewController];
}

- (OnboardingViewController *)generateStandardOnboardingVC {
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    
    PPLeadViewController *firstPage = [PPLeadViewController contentWithTitle:@"" body:@"" image:[UIImage imageNamed:@"loadpage1"] buttonText:@"" action:^{
    }];
    
    PPLeadViewController *secondPage = [PPLeadViewController contentWithTitle:@"" body:@"" image:[UIImage imageNamed:@"loadpage2"] buttonText:@"" action:^{
    }];
    
    PPLeadViewController *thirdPage = [PPLeadViewController contentWithTitle:@"" body:@"" image:[UIImage imageNamed:@"loadpage3"] buttonText:@"" action:^{
    }];
    
    PPLeadViewController *forthPage = [PPLeadViewController contentWithTitle:@"" body:@"" image:[UIImage imageNamed:@"loadpage4"] buttonText:@"" action:^{
        [self handleOnboardingCompletion];
        [[TTGlobalStatus sharedStatus].globalStatusDefault setValue:@"1" forKey:@"start_guide_status"];
        [[TTGlobalStatus sharedStatus].globalStatusDefault synchronize];
    }];
    
    OnboardingViewController *onboardingVC = [OnboardingViewController onboardWithBackgroundImage:[UIImage imageNamed:@"street"] contents:@[firstPage, secondPage, thirdPage, forthPage]];
    onboardingVC.shouldFadeTransitions = YES;
    onboardingVC.fadePageControlOnLastPage = YES;
    onboardingVC.fadeSkipButtonOnLastPage = YES;
//    onboardingVC.allowSkipping = YES;
    onboardingVC.pageControl.pageIndicatorTintColor = PP_Default_Color_Gray_F1F1F1;
    onboardingVC.pageControl.currentPageIndicatorTintColor = PP_Default_Color_Red_FF3737;

    onboardingVC.skipHandler = ^{
        [self handleOnboardingCompletion];
        [[TTGlobalStatus sharedStatus].globalStatusDefault setValue:@"1" forKey:@"start_guide_status"];
        [[TTGlobalStatus sharedStatus].globalStatusDefault synchronize];
    };
    
    firstPage.topPadding = 0;
    firstPage.bottomPadding = 0;
    firstPage.iconWidth = TTScreenWidth;
    firstPage.iconHeight = TTScreenHeight;
    
    secondPage.topPadding = 0;
    secondPage.bottomPadding = 0;
    secondPage.iconWidth = TTScreenWidth;
    secondPage.iconHeight = TTScreenHeight;
    
    thirdPage.topPadding = 0;
    thirdPage.bottomPadding = 0;
    thirdPage.iconWidth = TTScreenWidth;
    thirdPage.iconHeight = TTScreenHeight;
    
    forthPage.topPadding = 0;
    forthPage.bottomPadding = 0;
    forthPage.iconWidth = TTScreenWidth;
    forthPage.iconHeight = TTScreenHeight;
    
    return onboardingVC;
}


#pragma mark Pay-----------------------------Pay Method----------------------------------Pay
#pragma mark - openURL

- (NSMutableDictionary *)getParams:(NSString *)str
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    NSArray *item = [str componentsSeparatedByString:@"&"];
    for (NSString *param in item) {
        NSArray *paramArray = [param componentsSeparatedByString:@"="];
        [dict setObject:[NSString stringWithFormat:@"%@", paramArray[1]] forKey:paramArray[0]];
    }
    return dict;
}

// NOTE: 9.0以后使用新API接口
#pragma mark 外部激活及支付宝微信支付回调
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{

    if([[url absoluteString] rangeOfString:@"ppdlcall://"].location == 0) {
        
        NSString *urlStr = [url absoluteString];
        if ([urlStr hasPrefix:@"ppdlcall://"]) {

            NSString *parameter = [urlStr stringByReplacingOccurrencesOfString:@"ppdlcall://param?" withString:@""];
            
            if (![parameter hasPrefix:@"ppdlcall://"]) {
                NSDictionary *dic = [Utilities getParams:parameter];

                PP_jumpModel *model = [[PP_jumpModel alloc] init];
                model.type = (CommentClickType)[[dic valueForKey:@"type"] integerValue];
                model.ID = [dic valueForKey:@"id"];
                model.ext = dic.mutableCopy;
                [[TTJumpManager share] pushViewControllerWithModel:model];
                
            } else {
                
            }
        }
    }
    
    if([[url absoluteString] rangeOfString:@"wxf90fd221278b8b0f://"].location == 0) {
        [WXApi handleOpenURL:url delegate:self];
    }
    
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            NSString * isPaySuccess = @"0";
            NSString * msg = [resultDic objectForKey:@"memo"];;
            switch ([[resultDic objectForKey:@"resultStatus"] integerValue]) {
                case 6001:
                {
                    isPaySuccess = @"0";
                    msg = @"用户中途取消";
                    
                }
                    break;
                    
                case 6002:
                {
                    isPaySuccess = @"0";
                    msg = @"网络连接出错";
                }
                    break;
                    
                case 6004:
                {
                    isPaySuccess = @"0";
                    msg = @"支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态";
                    
                }
                    break;
                    
                case 4000:
                {
                    isPaySuccess = @"0";
                    msg = @"支付失败";
                }
                    break;
                    
                case 8000:
                {
                    isPaySuccess = @"0";
                    msg = @"正在处理中，支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态";
                }
                    break;
                    
                case 9000:
                {
                    isPaySuccess = @"1";
                    msg = @"支付成功";
                    
                }
                    break;
                    
                default:
                    break;
            }
            
            NSMutableDictionary *payDic = @{}.mutableCopy;
            [payDic setValue:msg forKey:@"memo"];
            [payDic setValue:msg forKey:@"msg"];
            [payDic setValue:@"alipay" forKey:@"payType"];

            [payDic setValue:isPaySuccess forKey:@"resultStatus"];
            [payDic setValue:[resultDic objectForKey:@"resultStatus"] forKey:@"code"];

            [[NSNotificationCenter defaultCenter] postNotificationName:@"payResultNotification" object:nil userInfo:payDic];
        }];
    }
    return YES;
}

#pragma mark - WX-----------------------------WX-----------------------------callback
/*! @brief 收到一个来自微信的请求，第三方应用程序处理完后调用sendResp向微信发送结果
 *
 * 收到一个来自微信的请求，异步处理完成后必须调用sendResp发送处理结果给微信。
 * 可能收到的请求有GetMessageFromWXReq、ShowMessageFromWXReq等。
 * @param req 具体请求内容，是自动释放的
 */
-(void) onReq:(BaseReq*)req{
    
}

/*! @brief 发送一个sendReq后，收到微信的回应
 *
 * 收到一个来自微信的处理结果。调用一次sendReq后会收到onResp。
 * 可能收到的处理结果有SendMessageToWXResp、SendAuthResp等。
 * @param resp resp
 */
-(void) onResp:(BaseResp*)resp{
    //判断是否是微信支付回调 (注意是PayResp 而不是PayReq)
    
    if ([resp isKindOfClass:[PayResp class]]) {
        //支付返回的结果, 实际支付结果需要去微信服务器端查询
        NSString *isPaySuccess = @"0";
        NSString *msg = @"";
        id errorCode = @(resp.errCode);

        switch (resp.errCode)
        {
            case WXSuccess:
            {
                isPaySuccess = @"1";
                msg = @"支付成功";
                
                break;
            }
            case WXErrCodeUserCancel:
            {
                isPaySuccess = @"0";
                msg = @"用户取消了支付";
                
                break;
            }
            default:
            {
                isPaySuccess = @"0";
                msg = @"支付失败";
                break;
            }
        }
        
        NSMutableDictionary *payDic = @{}.mutableCopy;
        [payDic setValue:msg forKey:@"memo"];
        [payDic setValue:msg forKey:@"msg"];
        [payDic setValue:@"wechat" forKey:@"payType"];
        [payDic setValue:errorCode forKey:@"code"];
        [payDic setValue:isPaySuccess forKey:@"resultStatus"];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"payResultNotification" object:nil userInfo:payDic];
        
    } else if ([resp isKindOfClass:[SendAuthResp class]]) {
        
        SendAuthResp* authResp = (SendAuthResp*)resp;
        NSLog(@"%ld",(long)authResp.errCode);
        NSLog(@"%@",authResp.code);
        

        NSMutableDictionary *payDic = @{}.mutableCopy;
        [payDic setValue:authResp.code forKey:@"code"];

        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PP_SendAuthRespNotification" object:nil userInfo:payDic];
        
        NSLog(@"发出通知");
        
    }
}

@end
